# -*- coding: utf-8 -*-
import uuid
from django.db import models
from home.utils.array_utils import ListTools
from home.utils.string_utils import StringUtils


class Article_Info(models.Model):
	"""
	文章信息表
	"""
	# ID
	id = models.CharField(max_length=64, primary_key=True)
	# 分类ID
	category_id = models.CharField(max_length=64)
	# 标题
	title = models.CharField(max_length=128)
	# 作者
	author = models.CharField(max_length=64)
	# 摘要
	summary = models.CharField(max_length=255)
	# 评论数量
	comment_count = models.BigIntegerField(default=0)
	# 阅读次数
	view_count = models.BigIntegerField(default=0)
	# 是否原创
	original = models.BooleanField(default=False)
	# 首页图片
	pic_id = models.CharField(max_length=64, default=None, null=True)
	# 创建时间
	create_time = models.DateTimeField()
	# 最后更新时间
	update_time = models.DateTimeField()
	
	def set_new_id(self, _id=None):
		"""
		为对象设置一个ID，如果传入的ID为空，则生成一个新的ID
		:param _id:
		:return:
		"""
		if _id is None or StringUtils.isEmpty(_id):
			self.id = Article_Info.create_id()
		else:
			self.id = _id
			
	def increase_view_count(self, count=1):
		"""
		增加文章计数
		:param count:1
		:return:
		"""
		if self.view_count is None:
			self.view_count = 0
		self.view_count = self.view_count + count
		
	def increase_comment_count(self, count=1):
		"""
		增加文章计数
		:param count:1
		:return:
		"""
		if self.comment_count is None:
			self.comment_count = 0
		self.comment_count = self.comment_count + count
		
	@staticmethod
	def create_id():
		"""
		生成一个唯一的64位UUID编码\n
		:return: like '525f1e08-debf-4fdc-9f73-47d67f2503af'
		"""
		return str(uuid.uuid4())
	
	class Meta:
		app_label = 'home'


class Article_Info_Serializer:
	@classmethod
	def to_json_object(cls, entity):
		keys = (
			"id", "category_id", "title", "author", "summary", "comment_count", "view_count", "original", "pic_id", "create_time", "update_time")
		json_obj = {}
		for key in keys:
			if entity.__getattribute__(key) is not None:
				value_type = type(entity.__getattribute__(key)).__name__
				if "datetime" == value_type or "time" == value_type:
					json_obj[key] = entity.__getattribute__(key).strftime("%Y-%m-%d %H:%M:%S")
				else:
					json_obj[key] = entity.__getattribute__(key)
		return json_obj
	
	@classmethod
	def to_json_objects(cls, entities):
		json_objs = []
		if ListTools.isNotEmpty(entities):
			for entity in entities:
				json_obj = cls.to_json_object(entity)
				json_objs.append(json_obj)
		return json_objs